package com.ssy.lingxi.member.merchant.handler.validator;

import com.ssy.lingxi.member.merchant.handler.annotation.MemberClassifyCodeAnnotation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 会员配置资料状态参数校验类
 * <p>用于检验接口VO参数的字段是否为自定义的状态枚举</p>
 * @author 万宁
 * @version 2.0.0
 * @date 2020-06-01
 */
public class MemberClassifyCodeValidator implements ConstraintValidator<MemberClassifyCodeAnnotation, String> {
    private boolean required = true;
    private int maxLength = 0;

    @Override
    public void initialize(MemberClassifyCodeAnnotation constraintAnnotation) {
        required = constraintAnnotation.required();
        maxLength = constraintAnnotation.max_length();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if(!required) {
            return true;
        }

        if(value == null || "".equals(value) || value.length() > maxLength) {
            return false;
        }

        String pattern = "^[a-z0-9A-Z_-]+$";
        return value.matches(pattern);
    }
}
